/**
 * 规则列表
 */
define(['../../common/service'],function(http){
    var RuleScriptList = {
        init : function(){
            var _this = this;
            //初始化tab
            $("div.ndp-tab-wrapper[name=plain-tab]").tabs({
                list:[I18N.getText("rulescriptList","roleListTitle"),
                    I18N.getText("rulescriptResult","ruleResult"),
                    I18N.getText("optRecords","optRecords"),
                    I18N.getText("rulescriptSetting","setting")]
            }).on("TAB_CHANGE",function(e){//点击其中的一个tab发生事件
                var href = "";
                switch (e.originalEvent.data.index){
                    case 0:
                        href = "#!rulescriptList";
                        break;
                    case 1:
                        href = "#!rulescriptResult";
                        break;
                    case 2:
                        href = "#!optRecords";
                        break;
                    case 3:
                        href = "#!rulescriptSetting";
                        break;
                }
                window.location.hash = href;
            }).val(0);//设置选中的tab 索引，默认0;

            //列表管理
            $('[list-manager="rule-script-list"]').listManager('init', {
                isRealTime:true
                ,setTopVal:175//调整吸顶的高度,需要减去这个高度
                ,scrollDOM:$('.fmp-article')//监听滚动条
                ,supportAjaxPage: true		//是否支持配置列表ajxa分页[多列表两种状态都有时，统一配置为true,禁用的列表pageJson参数为空即可]
                ,pageCallback:function(query){
                    _this._initList(query);
                }
            }, function(query){
                _this._initList(query);
                _this._optRetry();
                _this._optExecute();
            });
        },
        _initList : function(_query){
            var _this = this;
            //遮罩
            var loadingArea = $('.container-fluid');
            Kit.loading.show(loadingArea);

            http.work('/rulescript/list',_query,'POST').then(function(res){
                //操作DOM节点更换数据
                var _table = $('table[list-manager="rule-script-list"]'),
                    _tbody = $('tbody', _table),
                    tmpHtml = '',
                    _list = res.data.rules;

                for (var i = 0; i < _list.length; i++) {
                    tmpHtml += _this. _generateHTML(_list[i], i + 1);
                }
                _tbody.html(tmpHtml);
                _table.listManager([{'resetTd':false, 'resetPageData': res.data.paginator}]);
                //隐藏遮罩
                Kit.loading.hide(loadingArea);
            });
        },
        _generateHTML : function (obj, _serial){
            var _this = this;
            var tmpHtml = '<tr data-id="' + (obj.id || '') + '"' + '>'
                +  '<td>'
                + _serial
                + '</td>';

            //规则名称
            tmpHtml += '<td>'
                + '<a class="btn btn-link" href="?id=' + obj.id + '#!rulescriptDetail">' + obj.ruleName + '</a>'
                + '</td>';

            //版本
            tmpHtml += '<td>'
                + obj.version
                + '</td>';

            //是否运行
            tmpHtml += '<td>'
                + (obj.isRun === 0 ? '否' : '是' )
                + '</td>';

            //日数据周期
            tmpHtml += '<td>'
                + (obj.dataCycle || '0')
                + '天</td>';

            //快照数据周期 未设置则与日数据周期一样
            tmpHtml += '<td>'
                + (obj.snapCycle || '0')
                + '天</td>';

            //日志级别
            tmpHtml += '<td>'
                + _this._parseLogLevel(obj.logLevel)
                + '</td>';

            //脚本语言
            tmpHtml += '<td>'
                + obj.ruleEngine
                + '</td>';

            //创建时间
            tmpHtml += '<td>'
                + obj.createTime
                + '</td>';
            //操作
            tmpHtml += '<td>' +
                '<a href="javascript:;" class="opt-execute icon-btn" data-id="' + (obj.id || '') + '" title="'+I18N.getText("rulescriptList","doExecute")+'"><i class="fa fa-cog fa-lg"></i></a>' +
                '&nbsp;&nbsp;  | &nbsp;&nbsp; <a href="javascript:;" class="opt-retry icon-btn"  data-id="' + (obj.id || '') + '" title="'+I18N.getText("rulescriptList","doCompile")+'"><i class="fa fa-refresh fa-lg"></i></a>' +
                '</td>';

            tmpHtml += '</tr>';
            return tmpHtml;
        },
        _parseLogLevel : function(_level){
            switch (_level) {
                case 0:
                    return 'ERROR';
                case 1:
                    return 'WARN';
                case 2:
                    return 'INFO';
                case 3:
                default:
                    return 'DEBUG';
            }
        },
        /**
         * [optExecute 编译脚本]
         * @param  {[type]} e [description]
         * @return {[type]}   [description]
         */
        _optExecute: function() {
            $("tbody").off('click', '.opt-execute').on("click", '.opt-execute', function(){
                var id = $(this).data('id');
                //遮罩
                var loadingArea = $('.container-fluid');
                Kit.loading.show(loadingArea);

                http.work('/rulescript/recompile',{id : id},'POST').then(function(res){
                    if (res.flag == 'success'){
                        Kit.alert_success(I18N.getText("rulescriptList","exeSuccess"));
                    } else {
                        Kit.alert2(res.msg || I18N.getText("rulescriptList","exeFailed"))
                    }
                    Kit.loading.hide(loadingArea);
                });
            });
        },
        /**
         * [optRetry 重新执行]
         * @param  {[type]} e [description]
         * @return {[type]}   [description]
         */
        _optRetry: function() {
            $("tbody").off('click', '.opt-retry').on('click', '.opt-retry', function(){
                var id = $(this).data('id');
                //遮罩
                var loadingArea = $('.container-fluid');
                Kit.loading.show(loadingArea);

                http.work('/rulescript/redoRunLastSnap',{id : id},'POST').then(function(res){
                    if (res.flag == 'success'){
                        Kit.alert_success(I18N.getText("rulescriptList","exeSuccess"));
                    } else {
                        Kit.alert2(res.msg || I18N.getText("rulescriptList","exeFailed"));
                    }

                    Kit.loading.hide(loadingArea);
                });
            })
        }
    }

    return RuleScriptList;
});
